package funcSless

import (
	"fmt"
)

// 函数原型定义
type SlessFunc func(ctx *Context, owner string, sessionInfo *SessionInfo, msg []byte) ([]byte, error)

type SessionInfo struct {
	OpenId     string `json:"openId"`
	SessionKey string `json:"sessionKey,omitempty"`
}

// 调用一个函数
func CallFunc(
	funcId int32,
	owner string,
	sessionInfo *SessionInfo,
	msg []byte,
) ([]byte, error) {
	funcInst, ok := gFuncSlessEnv.FuncMap[funcId]
	if !ok {
		return nil, fmt.Errorf("func %d not found", funcId)
	}
	ctx := NewContext()

	//解锁，存档等善后逻辑
	defer ctx.EndCall()

	//调用函数
	re, err := funcInst(ctx, owner, sessionInfo, msg)
	if err != nil {
		return nil, err
	}

	return re, nil
}
